#include <iostream>
#include "Socket.hpp"
#include <sys/select.h>
#include <memory>
#include <algorithm>
#define NUM sizeof(fd_set) * 8
using namespace LogModule;
class SelectServer
{
public:
    SelectServer(int port)
        : _listen_socket(std::make_unique<TcpSocket>(port)), _isrunning(false)
    {
    }
    ~SelectServer()
    {
    }
    void Init()
    {
        _listen_socket->BuildTcpSocket();
        for (int i = 0; i < NUM; i++)
            fd_arry[i] = -1;
        fd_arry[0] = _listen_socket->Fd();
    }
    void Start()
    {
        _isrunning = true;
        //
        while (_isrunning)
        {
            int maxfd = -1;
            fd_set rfds;
            // 初始化
            FD_ZERO(&rfds);
            FD_SET(_listen_socket->Fd(), &rfds);
            for (int i = 0; i < NUM; i++)
            {
                if (fd_arry[i] == -1)
                    continue;
                FD_SET(fd_arry[i], &rfds);
                if (fd_arry[i] > maxfd)
                {
                    maxfd = fd_arry[i];
                }
                // std::cout<<"将sockfd "<<fd_arry[i]<<"设置进rfds"<<std::endl;
            }
            // if(FD_ISSET(_listen_socket->Fd(),&rfds))
            // {
            //     std::cout<<"设置成功"<<std::endl;
            // }
            // else
            // {
            //     std::cout<<"设置失败"<<std::endl;
            // }
            struct timeval timeout;
            timeout.tv_sec = 10;
            timeout.tv_usec = 0;
            // 注意nfds！！！！！
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);
            if (n > 0)
            {
                LOG(LogLevel::DEBUG) << "剩余时间 " << timeout.tv_sec << "." << timeout.tv_usec;
                Dispatcher(rfds);
            }
            else if (n == 0)
            {
                LOG(LogLevel::DEBUG) << "time out....";
            }
            else
            {
                LOG(LogLevel::ERROR) << "select error";
                return;
            }

            // InetAddr client;
            // int newsockfd = _listen_socket->Accept(&client);
            // LOG(LogLevel::DEBUG)<<"获得新连接: "<<newsockfd<<" "<<client.Ip()<<" "<<client.Port();
        }
        _isrunning = false;
    }
    void Dispatcher(fd_set &rfds)
    {
        for (int i = 0; i < NUM; i++)
        {
            if (fd_arry[i] == -1)
                continue;
            if (fd_arry[i] == _listen_socket->Fd())
            {
                if (FD_ISSET(_listen_socket->Fd(), &rfds))
                {
                    Accepter();
                }
            }
            else
            {
                if (FD_ISSET(fd_arry[i], &rfds))
                {
                    Recv(i);
                }
            }
        }
    }

    void Recv(int who)
    {
        char buffer[1024];
        int n = recv(fd_arry[who], buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;
            std::string message = "echo# ";
            message += buffer;
            send(fd_arry[who], message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出," << fd_arry[who];
            close(fd_arry[who]);
            fd_arry[who] = -1;
        }
        else
        {
            LOG(LogLevel::DEBUG) << "recv error," << fd_arry[who];
            close(fd_arry[who]);
            fd_arry[who] = -1;
        }
    }
    void Accepter()
    {
        InetAddr client;
        int newsockfd = _listen_socket->Accept(&client);
        LOG(LogLevel::DEBUG) << "获得新连接: " << newsockfd << " " << client.Ip() << " " << client.Port();
        // recv()?就一定有数据吗？
        int pos = -1;
        for (int i = 0; i < NUM; i++)
        {
            if (fd_arry[i] == -1)
            {
                pos = i;
                break;
            }
        }
        if (pos == -1)
        {
            LOG(LogLevel::DEBUG) << "服务器select管理的fd满了...";
        }
        else
        {
            fd_arry[pos] = newsockfd;
            //std::cout << "将newsockfd " << newsockfd << "设置进" << pos << " 辅助数组" << std::endl;
        }
    }

private:
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    int fd_arry[NUM]; // 辅助数组
};